<!-- 地图地点输入联想组件 -->
<template>
    <fragment>
        <el-autocomplete 
            :ref="'mpAtList'"
            prefix-icon="el-icon-map-location"
            popper-class="my-autocomplete"
            clearable
            :popper-append-to-body="false"
            :trigger-on-focus="clickShowList"
            :placeholder="placeholder"
            :fetch-suggestions="querySearchAsync"
            @select="handleSelect"
            @clear="handleClear"
            v-model="address"
            class="my-mplist"
        >
            <template slot-scope="{ item }">
                <div class="name" :title="item.name.length > 20 ? item.name : ''">
                    {{ item.name }}
                    <span class="c-yellow" v-if="item.type == 4">（虚拟）</span>
                </div>
                <span class="addr">
                    <template v-if="item.type == 4">无准确地址选择此项</template>
                    <template v-else>{{ item.address == '[]' ? '' : item.address }}（{{ item.area }}）</template>
                </span>
                <i v-if="item.isSta" class="sta-icon">站</i>
            </template>

            <template slot="append">
                <el-popover
                    placement="bottom"
                    :offset="0"
                    popper-class="mps-inp-list"
                    trigger="click"
                    v-model="popoverState"
                >
                    <el-form :class="name+'_'+pindex">
                        <el-form-item>
                            <MapPointInp 
                                :name="name" 
                                :placeholder="placeholder" 
                                @handleSel="selPoint" 
                                style="width: 100%;"
                            />
                        </el-form-item>

                        <el-form-item class="poi-list">
                            <label v-for="(tag, i) in poiList" :key="tag.id">
                                <el-tag
                                    closable
                                    size="medium"
                                    @close="delTag(i, tag)"
                                >{{tag.name}}</el-tag><b class="right-arrow" v-if="i != poiList.length - 1">→</b>
                            </label>
                        </el-form-item>

                        <div class="fm-btns">
                            <div class="btns">
                                <el-button type="primary" @click.native="savePoints">关 闭</el-button>
                            </div>
                            <div class="fun-explain">说明：如需要修改，请先删除再添加，可以拖动排序</div>
                        </div>
                    </el-form>

                    <span slot="reference" title="点击添加多个地点">{{poiList.length}}</span>
                </el-popover>
            </template>
        </el-autocomplete>
    </fragment>
</template>

<script>
import Sortable from 'sortablejs';
import MapPointInp from '@/components/MapPointInp';
import MapPoints from '@/components/MapPoints';

import * as commonService from '@/api/services/common.service';

export default {
  name: 'MapPointList',
  components: { MapPointInp, MapPoints },
  props: {
    // 当前点的参数名称 如：xxx.xxx
    name: {         
        require: true,
        type: String
    },
    // 地点所在数组下标（一般是列表数组所需）
    pindex: {         
        type: String,
        default: '0'
    },
    // 输入框内提示文本
    placeholder: {    
        type: String,
        default: '请输入地点关键字'
    },
    // 默认的地点
    vallist: {   
        type: Array,
        default: () => []
    }
  },
  watch: {
    // 监听父级传入的多个地点列表值
    // vallist(c, o){
    //     const that = this;

    //     that.poiList = c;
        
    //     // 设置输入框值
    //     that.address = c.length > 0 ? c[0].name : '';
    //     console.log('监听多地点默认值', c);
    // }

    vallist: {
        handler(c, o){
            this.poiList = c;
        
            // 设置输入框值
            this.address = c.length > 0 ? c[0].name : '';
            // console.log('**********监听多地点默认值', c);
        },
        deep: true,
        immediate: true
    }

  },
  data() { 
    return {
        // 默认点击显示建议面板
        clickShowList: false,
        // 选中地点地址    
        address: this.vallist.length > 0 ? this.vallist[0].name : '',

        // popover的显示/隐藏
        popoverState: false,
        // 已选择的点数组
        poiList: this.vallist || [],
    }
  },
  mounted() {
    const that = this;

    setTimeout(() => { that.tagSort(); }, 500);
  },
  created(){
    // console.log('传入的地点数组', this.poiList);
  },
  methods:{
    // 发送请求查询地址
    querySearchAsync(kw, cb) {
        const that = this;
        
        if(kw){// 存在搜索关键字，则请求后台获取地图地址
            commonService.getMapPointList({ keywords: kw }).then(res => {
                if(!res || res.code != 1){
                    that.U.qerror(res.msg);
                    cb([]);
                }else {
                    let list = res.data;
                    // console.log('请求数据', list);

                    let pois = [];
                    // 将请求后的数据，加入至列表
                    list.forEach(it => {
                        if(it.address == '[]') it.address = '';
                        if(it.address instanceof Array) it.address = it.address.join(',');
                        
                        pois.push({
                            id: it.id,              // id
                            lnglat: it.lnglat,      // 坐标
                            area: it.area,          // 区域
                            name: it.name,          // 名称
                            address: it.address,    // 地址
                            type: it.type,          // 地点类型
                            isSta: false            // 是否是站点
                        });
                    });
                    // console.log('结果数据', pois);

                    cb(pois);
                }
            });
        }
    },
    // 点击某项事件
    handleSelect(item) {
        const that = this;
        
        let p = that.poiList.findIndex(it => it.name == item.name);
        if(p == -1){// 不存在，则放到第一位
            that.poiList.unshift(item);
        }else{
            // 先删除
            that.poiList.splice(p, 1);
            // 再插入
            that.poiList.unshift(item);
        }
        // 设置输入框值
        that.address = that.poiList[0].name;

        that.$emit('handleSel', {name: that.name, pindex: that.pindex, p: that.poiList});
    },
    // 清空输入框值
    handleClear(){
        const that = this;
        
        // 删除首位
        if(that.poiList.length > 0) that.poiList.splice(0, 1);

        that.$emit('handleSel', {name: that.name, pindex: that.pindex, p: that.poiList});
    },

    // 标签-拖动排序
    tagSort() {
        const that = this;
        
        const el = document.querySelector(`.${that.name}_${that.pindex} .poi-list .el-form-item__content`);
        Sortable.create(el, {
            ghostClass: 'sortable-ghost',
            onEnd: evt => {
                const targetRow = that.poiList.splice(evt.oldIndex, 1)[0];
                that.poiList.splice(evt.newIndex, 0, targetRow);

                // 设置输入框值
                that.address = that.poiList[0].name;
                that.$emit('handleSel', {state: false, name: that.name, p: that.poiList});
            }
        });
    },
    // 选中某一个地点
    selPoint(e){ 
        const that = this;
        
        if(e.p){
            let index = that.poiList.findIndex(it => { return it.id == e.p.id; });
            if(index == -1) that.poiList.push(e.p);

            // 只有一个则设置值
            if(that.poiList.length == 1) that.address = that.poiList[0].name;

            that.$emit('handleSel', {state: false, name: that.name, pindex: that.pindex, p: that.poiList});
        }
    },
    // 删除
    delTag(i, tag){
        const that = this;

        that.U.qconfim(`确定删除[${tag.name}]地点吗？`).then(r => {
            if(r){
                that.poiList.splice(i, 1);

                // 删完了则清空第一个地点
                // if(that.poiList.length == 0) that.address = '';

                that.$emit('handleSel', {name: that.name, pindex: that.pindex, p: that.poiList});
            }
        });
    },
    // 保存-选择的地点列表
    savePoints(){
        const that = this;

        // 隐藏poverper
        that.popoverState = false;
    }

  }
}
</script>

<style lang="less">
    .my-mplist /deep/{
        .my-autocomplete{
            width: auto !important;

            li{
                position: relative;
                line-height: 20px !important;
                margin-bottom: 10px !important;
            }
        } 

        .el-input-group__append{
            padding: 0px !important;
            cursor: pointer;

            .el-popover__reference{
                display: inline-block;
                width: 24px;
                height: 26px;
                line-height: 26px;
                text-align: center;
            }
        }
    }
    
</style>

<style lang="less" scoped>
.my-mplist{
    .my-autocomplete{
        li {
            .name {
                max-width: 20em;
                text-overflow: ellipsis;
                overflow: hidden;
                text-align: left;
            }
            .addr {
                display: block;
                max-width: 24em;
                text-overflow: ellipsis;
                overflow: hidden;
                font-size: 12px;
                color: #b4b4b4;
                text-align: left;
            }

            .highlighted .addr {
                color: #ddd;
            }

            .sta-icon{
                position: absolute;
                bottom: 0px;
                left: 2px;
                color: #ff6300;
                font-size: 16px;
                display: inline-block;
                height: 100%;
                line-height: 40px;
                font-style: normal;
            }
        }
    }
}
.poi-list{
    border: 1px solid #efefef; 
    border-radius: 5px; 
    padding: 0px 5px 5px 5px;
    min-height: 50px;
    margin-bottom: 10px !important;

    ::v-deep {
        label{
            .right-arrow{
                padding-right: 10px;
            }
        }

        .sortable-ghost .el-tag{
            opacity: .8;
            color: #fff !important;
            background: #42b983 !important;
        }

        .el-tag {
            margin: 10px 10px 5px 0px;
            cursor: pointer;
        }
    }
}
</style>

<style lang="less">
.mps-inp-list{
    max-width: 80vh;
    min-width: 20vh;
    padding-bottom: 0 !important;
}
</style>